from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.utils import UserPageNum
from meiduo_admin.serializer.brand import BrandSerializer

from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from goods.models import Brand
from celery_tasks.detail_html.task import get_detail_html

class BrandView(ModelViewSet):

    # 指定查询集
    queryset = Brand.objects.all()
    # 指定序列化器
    serializer_class = BrandSerializer
    # 指定分页器
    pagination_class = UserPageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    # 重写创建表
    def create(self, request, *args, **kwargs):
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        image_data = request.FILES.get('logo')
        client = Fdfs_client(settings.FASTDFS_CONF)
        res = client.upload_by_buffer(image_data.read())
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        logo_url = res['Remote file_id']
        brand = Brand.objects.create(logo=logo_url,first_letter=first_letter,name=name)
        # 返回图片表对象
        return Response({
            "name": brand.name,
            "logo": brand.logo,
            "first_letter": brand.first_letter
       })

    def update(self, request, *args, **kwargs):
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        image_data = request.FILES.get('logo')
        client = Fdfs_client(settings.FASTDFS_CONF)
        res = client.upload_by_buffer(image_data.read())
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        logo_url = res['Remote file_id']

        Brand.objects.filter(id=kwargs['pk']).update(logo=logo_url,name=name,first_letter=first_letter)

        # brand = Brand.objects.get(id=kwargs['pk'])
        # brand.logo=logo_url
        # brand.name=name
        # brand.first_letter=first_letter
        # brand.save()

        return Response({
            "id": kwargs['pk'],
            "name": name,
            "logo": logo_url,
            "first_letter": first_letter
        })




